package me.zhengjie.modules.hanzi.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.hanzi.config.AiServiceProperties;
import me.zhengjie.modules.hanzi.service.AiHttpClient;
import me.zhengjie.modules.hanzi.service.HanziAiScoreService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用新配置系统的AI评分服务示例
 * 展示如何直接使用特定的AI服务提供商
 */
@Service("customAiScoreService")
@RequiredArgsConstructor
@Slf4j
public class CustomAiScoreServiceImpl implements HanziAiScoreService {
    
    private final AiServiceProperties aiServiceProperties;
    private final AiHttpClient aiHttpClient;
    
    @Override
    public Map<String, Object> scoreWithAI(String targetChar, MultipartFile userImage) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 示例：直接使用server配置
            var serverConfig = aiServiceProperties.getServer();
            
            if (!serverConfig.isEnabled()) {
                log.warn("Server AI服务未启用");
                return createErrorResult("Server AI服务未启用");
            }
            
            // 构建提示词
            String prompt = buildScoringPrompt(targetChar);
            
            // 调用AI服务
            String aiResponse = aiHttpClient.sendChatRequest(serverConfig, prompt, userImage);
            
            if (aiResponse == null || aiResponse.trim().isEmpty()) {
                log.warn("AI服务返回空响应");
                return createErrorResult("AI服务返回空响应");
            }
            
            // 解析响应并构建结果
            return parseAndBuildResult(aiResponse, targetChar);
            
        } catch (Exception e) {
            log.error("AI评分过程中发生错误", e);
            return createErrorResult("AI评分失败: " + e.getMessage());
        }
    }
    
    /**
     * 构建评分提示词
     */
    private String buildScoringPrompt(String targetChar) {
        return String.format(
            "你是一位专业的汉字书法评分专家。请分析用户书写的汉字\"%s\"。\n" +
            "\n" +
            "请从以下维度进行评分（每项满分100分）：\n" +
            "1. 字形准确度 (character_accuracy)\n" +
            "2. 笔画规范度 (stroke_standard)\n" +
            "3. 结构协调性 (structure_balance)\n" +
            "4. 整体美观度 (overall_beauty)\n" +
            "\n" +
            "请严格按照以下JSON格式返回评分结果：\n" +
            "{\n" +
            "  \"total_score\": <总分0-100>,\n" +
            "  \"character_accuracy\": <字形准确度0-100>,\n" +
            "  \"stroke_standard\": <笔画规范度0-100>,\n" +
            "  \"structure_balance\": <结构协调性0-100>,\n" +
            "  \"overall_beauty\": <整体美观度0-100>,\n" +
            "  \"detailed_feedback\": \"<详细评价>\",\n" +
            "  \"improvement_suggestions\": \"<改进建议>\",\n" +
            "  \"grade_level\": \"<等级>\"\n" +
            "}", targetChar);
    }
    
    /**
     * 解析AI响应并构建结果
     */
    private Map<String, Object> parseAndBuildResult(String aiResponse, String targetChar) {
        // 这里应该实现JSON解析逻辑
        // 为了示例，返回一个简单的结果
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("targetChar", targetChar);
        result.put("rawResponse", aiResponse);
        result.put("evaluationMethod", "CUSTOM_AI_SERVICE");
        
        // 在实际实现中，这里应该解析aiResponse的JSON内容
        // 并提取具体的评分数据
        
        return result;
    }
    
    /**
     * 创建错误结果
     */
    private Map<String, Object> createErrorResult(String errorMessage) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("error", errorMessage);
        return result;
    }
}